package com.example.myapplication.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.ImageView;

import com.example.myapplication.R;
import com.example.myapplication.bean.TeamGsonData;
import com.example.myapplication.utils.IP;
import com.squareup.picasso.Picasso;

public class TeamsAdapter extends BaseAdapter {
    private static final String TAG = "TeamsAdapter";
    private List<TeamGsonData.Team> objects = new ArrayList<>();

    private Context context;
    private LayoutInflater layoutInflater;

    public TeamsAdapter(Context context, List<TeamGsonData.Team> objects) {
        this.objects = objects;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return objects.size();
    }

    @Override
    public TeamGsonData.Team getItem(int position) {
        return objects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.list_item_teams, null);
            convertView.setTag(new ViewHolder(convertView));
        }
        initializeViews((TeamGsonData.Team) getItem(position), (ViewHolder) convertView.getTag());
        return convertView;
    }

    private void initializeViews(TeamGsonData.Team object, ViewHolder holder) {
        holder.tvTeamId.setText(object.getTeamGroup());
        holder.tvTeamName.setText(object.getTeamName());
        List<String> ipList = IP.getIpList();
        for (int i = 0; i < ipList.size(); i++) {
            try {
                Picasso.with(context)
                        .load("http://10.20.252.243:8080" + "/" + object.getTeamPic())
                        .into(holder.ivTeam);
                Log.d(TAG, "initializeViews: 请求图片成功");
                break;
            } catch (Exception e) {
                Log.d(TAG, "initializeViews: 请求图片失败");
            }
        }
    }

    protected class ViewHolder {
        private TextView tvTeamId;
        private ImageView ivTeam;
        private TextView tvTeamName;

        public ViewHolder(View view) {
            tvTeamId = (TextView) view.findViewById(R.id.tv_teamId);
            ivTeam = (ImageView) view.findViewById(R.id.iv_team);
            tvTeamName = (TextView) view.findViewById(R.id.tv_teamName);
        }
    }
}
